<template>
  <div>
    <span id="shareText"></span>
  </div>

  <t-button @click="OpenDisplayMedia"> 共享屏幕 </t-button>

  <t-button @click="OpenCameraVideoList"> 打开摄像头 </t-button>
  <t-dialog
    v-model:visible="cameraVideoVisible"
    draggable
    mode="modal"
    header="添加直播素材"
    :on-confirm="OpenCameraVideo"
  >
    <template #body>
      <t-select v-model="cameraVideoDeviceId" placeholder="请选择">
        <t-option v-for="item in cameraArr" :key="item.id" :value="item.id" :label="item.label"></t-option>
      </t-select>
    </template>
  </t-dialog>

  <t-button @click="handleOpenVideo"> 我要开播 </t-button>

  <div id="app">
    <!--本地视频流-->
    <div style="display: flex; justify-content: center; align-items: center; height: 100%">
      <div
        style="
          width: 960px;
          height: 540px;
          background-color: #f0f0f0;
          border: 1px solid #ccc;
          position: relative;
          overflow: hidden;
        "
      >
        <DraggableContainer>
          <Vue3DraggableResizable
            :initW="displayMediaData.initW"
            :initH="displayMediaData.initH"
            v-model:x="displayMediaData.x"
            v-model:y="displayMediaData.y"
            v-model:w="displayMediaData.w"
            v-model:h="displayMediaData.h"
            :active="displayMediaData.active"
            :draggable="true"
            v-show="displayMediaData.active"
            :resizable="true"
            :lockAspectRatio="true"
          >
            <video
              id="localDisplayMedia"
              style="width: 100%; height: 100%; cursor: move; object-fit: fill"
              autoplay
              muted
              playsinline
            >
              屏幕
            </video>
          </Vue3DraggableResizable>

          <Vue3DraggableResizable
            :initW="cameraVideoData.initW"
            :initH="cameraVideoData.initH"
            v-model:x="cameraVideoData.x"
            v-model:y="cameraVideoData.y"
            v-model:w="cameraVideoData.w"
            v-model:h="cameraVideoData.h"
            :active="cameraVideoData.active"
            :draggable="true"
            v-show="cameraVideoData.active"
            :resizable="true"
            :lockAspectRatio="true"
          >
            <video
              id="localCameraVideo"
              style="width: 100%; height: 100%; cursor: move; object-fit: fill"
              autoplay
              muted
              playsinline
            >
              摄像头
            </video>
          </Vue3DraggableResizable>
        </DraggableContainer>
      </div>
      <div
        style="
          width: 385px;
          height: 540px;
          border-radius: 5px;
          border-style: solid;
          border-width: 1px;
          border-color: #fff;

          background-color: #fff;
          margin-left: 10px;
        "
      >
        <h3 style="color: var(--text1)">素材列表</h3>
      </div>
    </div>

    <!-- 远程端视频流 -->
    <div style="display: flex; justify-content: center; align-items: center; height: 100%">
      <div style="width: 960px; height: 540px; background-color: #f0f0f0; border: 1px solid #ccc">
        <video id="remoteVideo" style="width: 100%; height: 100%" autoplay muted playsinline>远程视频</video>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { Vue3DraggableResizable, DraggableContainer } from 'vue3-draggable-resizable'
import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css'
import { doOfferPush } from '@/utils/rtc_push'
import { VideoStreamMerger } from 'video-stream-merger'
import { MessagePlugin } from 'tdesign-vue-next'

export default defineComponent({
  name: 'Home',
  components: { Vue3DraggableResizable },
  data() {
    return {
      cameraArr: [],
      cameraVideoDeviceId: null,
      cameraVideoVisible: false,
      roomId: Math.random().toString(36).substring(2),
      userId: Math.random().toString(36).substring(2),
      displayMediaData: {
        initW: 0,
        initH: 0,
        x: 0,
        y: 0,
        h: 100,
        w: 100,
        active: false,
        srcObject: null,
      },
      cameraVideoData: {
        initW: 0,
        initH: 0,
        x: 650,
        y: 450,
        h: 100,
        w: 100,
        active: false,
        srcObject: null,
      },
    }
  },
  methods: {
    OpenDisplayMedia() {
      // 屏幕共享
      var _this = this
      var localDisplayMedia = document.getElementById('localDisplayMedia') as HTMLVideoElement
      try {
        navigator.mediaDevices.getDisplayMedia({ audio: true, video: true }).then(function (stream) {
          var streamInfo = stream.getVideoTracks()[0].getSettings()
          _this.displayMediaData.w = 900
          _this.displayMediaData.h = streamInfo.height / (streamInfo.width / _this.displayMediaData.w)
          localDisplayMedia.srcObject = stream
          _this.displayMediaData.srcObject = stream
          _this.displayMediaData.active = true
        })
      } catch (e) {
        MessagePlugin.closeAll()
        MessagePlugin.error('屏幕分享失败')
      }
    },

    OpenCameraVideoList() {
      // 打开摄像头列表
      var _this = this
      _this.cameraArr = []
      this.cameraVideoVisible = true
      navigator.mediaDevices.enumerateDevices().then(function (devices) {
        devices.forEach(function (device) {
          if (device.kind == 'videoinput') {
            _this.cameraArr.push({
              label: device.label,
              id: device.deviceId,
            })
          }
        })
      })
    },

    OpenCameraVideo() {
      // 打开摄像头列表
      var _this = this
      var localCameraVideo = document.getElementById('localCameraVideo') as HTMLVideoElement

      try {
        navigator.mediaDevices
          .getUserMedia({
            audio: true,
            video: { deviceId: _this.cameraVideoDeviceId },
          })
          .then(function (stream) {
            var cameraInfo = stream.getVideoTracks()[0].getSettings()
            _this.cameraVideoData.w = 180
            _this.cameraVideoData.h = cameraInfo.height / (cameraInfo.width / _this.cameraVideoData.w)
            localCameraVideo.srcObject = stream
            _this.cameraVideoData.srcObject = stream
            _this.cameraVideoData.active = true
          })
      } catch (e) {
        MessagePlugin.closeAll()
        MessagePlugin.error('打开摄像头失败')
      }
      this.cameraVideoVisible = false
    },

    handleOpenVideo() {
      // 初始化本地码流

      var merger = new VideoStreamMerger({
        width: 960, // Width of the output video
        height: 646, // Height of the output video
        clearRect: true,
        fps: null,
        audioContext: null, // 提供正确的 AudioContext 对象
      })

      if (this.displayMediaData.srcObject) {
        console.log(this.displayMediaData)
        merger.addStream(this.displayMediaData.srcObject, {
          x: this.displayMediaData.x,
          y: this.displayMediaData.y,
          width: this.displayMediaData.w,
          height: this.displayMediaData.h,
          muted: true,
          index: 0, // Layer on which to draw the stream (0 is bottom, 1 is above that, and so on)
          mute: true, // if true, any audio tracks will not be merged
          draw: null, // A custom drawing function (see below)
          audioEffect: null, // A custom WebAudio effect (see below)
        })
      }

      if (this.cameraVideoData.srcObject) {
        console.log(this.cameraVideoData)
        merger.addStream(this.cameraVideoData.srcObject, {
          x: this.cameraVideoData.x,
          y: this.cameraVideoData.y,
          width: this.cameraVideoData.w,
          height: this.cameraVideoData.h,
          muted: false,
          index: 0, // Layer on which to draw the stream (0 is bottom, 1 is above that, and so on)
          mute: false, // if true, any audio tracks will not be merged
          draw: null, // A custom drawing function (see below)
          audioEffect: null, // A custom WebAudio effect (see below)
        })
      }

      merger.start()
      var remoteVideo = document.getElementById('remoteVideo') as HTMLVideoElement
      remoteVideo.srcObject = merger.result
      doOfferPush(this.userId, this.roomId, merger.result)
    },
  },
})
</script>

<style>
body {
  background-image: url(/assets/background.jpg);
  width: 1440px;
}
</style>
